<?php

namespace Admin\Controller;

use Admin\Model\SysAccountModel;
use Admin\Model\UserAccountModel;
use Admin\Model\UserModel;
use Think\Exception;
use Think\Think;

class UserController extends AdminController {

    protected $page_size;

    public function __construct() {
        parent::__construct();

        $this->page_size = C('PAGE_SIZE') > 0 ? C('PAGE_SIZE') : 20;
    }

    public function index() {
        $mobile = I('mobile', '', 'trim');
        $email = I('email', '', 'trim');
        $nickname = I('nickname', '', 'trim');
        $identity = I('identity', '');
        $where = [];

        if ($mobile) {
            $where['mobile'] = ['like', '%' . $mobile . '%'];
        }
        if ($email) {
            $where['email'] = ['like', '%' . $email . '%'];
        }
        if ($nickname) {
            $where['nickname'] = ['like', '%' . $nickname . '%'];
        }

        if (is_numeric($identity)) {
            $where['identity'] = $identity;
        }

        $total = M('User')->where($where)->count();
        $Page = new \Think\Page($total, $this->page_size);
        $result = M('User')->where($where)->page($Page->nowPage, $Page->listRows)->order('id DESC')->select();

        $this->assign('page', $Page->show());
        $this->assign('result', $result);
        $this->display();
    }

    public function wealth() {
        $nickname = I('nickname', '', 'trim');
        $identity = I('identity', '');
        $where = [];
        if ($nickname) {
            $where['B.mobile'] = $nickname;
        }

        if (is_numeric($identity)) {
            $where['B.identity'] = $identity;
        }
        $count = M('UserWealth')->alias('A')->field('A.id')
            ->join(C('DB_PREFIX') . 'user as B ON A.user_id = B.id', 'left')
            ->where($where)->count();
        $Page = new \Think\Page($count, $this->page_size);
        $result = M('UserWealth')->alias('A')->field('A.*,B.nickname,B.identity')
            ->join(C('DB_PREFIX') . 'user as B ON A.user_id = B.id', 'left')
            ->where($where)->page($Page->nowPage, $Page->listRows)->order('id DESC')->select();

        $total =[];
        $total['balance'] = M('UserWealth')->alias('A')->join(C('DB_PREFIX') . 'user as B ON A.user_id = B.id', 'left')->where($where)->sum('balance');
        $total['integral'] = M('UserWealth')->alias('A')->join(C('DB_PREFIX') . 'user as B ON A.user_id = B.id', 'left')->where($where)->sum('integral');
        $total['coupon'] = M('UserWealth')->alias('A')->join(C('DB_PREFIX') . 'user as B ON A.user_id = B.id', 'left')->where($where)->sum('coupon');
        $total['stored_integral'] = M('UserWealth')->alias('A')->join(C('DB_PREFIX') . 'user as B ON A.user_id = B.id', 'left')->where($where)->sum('stored_integral');
        $total['unstore_integral'] = M('UserWealth')->alias('A')->join(C('DB_PREFIX') . 'user as B ON A.user_id = B.id', 'left')->where($where)->sum('unstore_integral');

        $this->assign([
            'result' => $result,
            'page' => $Page->show(),
            'total' => $total,
        ]);

        $this->display();
    }

    //用户详情
    public function detail() {
        $id = I('id', 0, 'intval');
        $user_info = M('User')->alias('A')->join(C('DB_PREFIX') . 'user_wealth as B ON A.id = B.user_id', 'LEFT')->find($id);
        $inviter = [];
        $parent = $this->getParents($user_info['id']);
        if ($parent) {
            $parent = array_reverse($parent);
            foreach ($parent as $item) {
                $inviter[] = $item['nickname'] . ' [' . userIdentity($item['identity']) . '] ';
            }
        }

        $this->assign('id', $id);
        $this->assign($user_info);
        $this->assign('invit_string', implode(' > ', $inviter));
        $this->display();
    }

    //用户激活申请记录
    public function active() {
        $keyword = I('keyword',0,'intval');

        $where = [];
        if(!empty($keyword)){
            $where['user_id'] = $keyword;
        }

        $UserActiving = M('UserActiving');
        $count = $UserActiving->where($where)->count();
        $Page = new \Think\Page($count, $this->page_size);
        $result = $UserActiving->where($where)
            ->page($Page->nowPage, $Page->listRows)
            ->order('status ASC,created_at DESC')
            ->select();

        $users = $users = M('User')->field('password,token', true)->select();
        $news = [];
        foreach ($users as $user) {
            $news[$user['id']] = $user;
        }

        $this->assign([
            'page' => $Page->show(),
            'result' => $result,
            'users' => $news,
        ]);

        $this->display();
    }

    //用户激活申请记录
    public function renewal() {
        $where = [];
        $UserActiving = M('UserRenewal');
        $count = $UserActiving->where($where)->count();
        $Page = new \Think\Page($count, $this->page_size);
        $result = $UserActiving->where($where)
            ->page($Page->nowPage, $Page->listRows)
            ->order('status ASC,created_at DESC')
            ->select();

        $users = $users = M('User')->field('password,token', true)->select();
        $news = [];
        foreach ($users as $user) {
            $news[$user['id']] = $user;
        }

        $this->assign([
            'page' => $Page->show(),
            'result' => $result,
            'users' => $news,
        ]);

        $this->display();
    }

    //确认激活用户
    public function active_success() {
        $id = I('get.id', 0, 'intval');
        if (empty($id)) {
            $this->error('参数错误');
            return;
        }

        //模型
        $UserActiving = M('UserActiving');
        $User = M('User');
        $UserWealth = M('UserWealth');

        //提交的申请记录
        $info = $UserActiving->find($id);
        if (empty($info)) {
            $this->error('信息不存在');
            return;
        }

        if ($info['status'] != 0) {
            $this->error('该申请已处理');
            return;
        }

        if ($info['amount'] < $this->setting['min_user_active_amount'] || $info['amount'] % $this->setting['min_user_active_amount'] != 0) {
            $this->error('报单金额有误');
            return;
        }

        //获取运营中心信息
        $applier = $User->alias('A')->join(C('DB_PREFIX') . "user_wealth as B ON A.id = B.user_id", 'left')
            ->where(['id' => $info['apply_id']])->find();
        if (empty($applier)) {
            $this->error('运营中心不存在，请核实');
            return;
        }

        if ($applier['identity'] != UserModel::USER_SUPPLIER && $applier['identity'] != UserModel::USER_SUPPER_SUPPLIER) {
            $this->error('该用户不是运营中心身份');
            return;
        }

        $need_balance = 0;  //需要缴纳的现金
        $need_integral = 0;  //需要缴纳的积分

        if ($info['pay_type'] == 1) {
            //全额现金
            $need_balance = $info['amount'];
        } else {
            $balance_percent = sprintf('%.2f', $this->setting['pay_balance_percent'] / 100);
            $need_balance = $balance_percent * $info['amount'];  //根据比例算出需要的现金
            $need_integral = $info['amount'] - $need_balance;  //需要的积分
        }

        //检查运营中心的现金和积分够不够
        if ($applier['integral'] < $need_integral) {
            $this->error('积分不足');
            return;
        }

        if ($applier['balance'] < $need_balance) {
            $this->error('现金余额不足');
            return;
        }

        //需要激活的用户
        $activeUser = $User->alias('A')->join(C('DB_PREFIX') . "user_wealth as B ON A.id = B.user_id", 'left')
            ->where(['id' => $info['user_id']])->find();
        if (empty($activeUser)) {
            $this->error('需要激活的用户不存在');
            return;
        }

        if ($activeUser['identity'] != 0) {
            $this->error('该用户已是激活状态，无需再次激活');
            return;
        }

        $p_parents = $this->getParents($info['user_id']);
        $activeUser['p_parent'] = []; //上上级

        if (!empty($p_parents)) {
            foreach ($p_parents as $item) {
                if ($item['level'] == 2) {
                    $activeUser['p_parent'] = $item;
                    break;
                }
            }
            unset($p_parents);
        }

        M()->startTrans();
        try {
            //扣除运营中心费用
            $data = [];
            $data['balance'] = array('exp', "balance-{$need_balance}");
            if ($need_integral > 0) {
                $data['integral'] = array('exp', "integral-{$need_integral}");
            }

            $UserWealth->where(['user_id' => $applier['id']])->save($data);
            //写入运营中心日志记录
            $userAccountData = [
                [
                    'user_id' => $applier['id'],
                    'amount' => $need_balance,
                    'balance' => $applier['balance'] - $need_balance,
                    'remark' => "申请下级用户【{$activeUser['nickname']}】激活，扣除现金{$need_balance}",
                    'created_at' => time(),
                    'type_id' => UserAccountModel::OP_CASH,
                    'source' => UserAccountModel::SC_OUT,
                ],
            ];

            if ($info['pay_type'] == 2) {
                $userAccountData[] = [
                    'user_id' => $applier['id'],
                    'amount' => $need_integral,
                    'balance' => $applier['integral'] - $need_integral,
                    'remark' => "申请下级用户【{$activeUser['nickname']}】激活，扣除积分{$need_integral}",
                    'created_at' => time(),
                    'type_id' => UserAccountModel::OP_INTEGRAL,
                    'source' => UserAccountModel::SC_OUT,
                ];
            }
            if (M('UserAccount')->addAll($userAccountData) === false) {
                throw new Exception(M('UserAccount')->getError());
            }
            //写入系统日志记录
            $sysAccountData = [];
            $sys_applier_data_1 = [
                'user_id' => $applier['id'],
                'amount' => $need_balance,
                'remark' => "运营中心【{$applier['nickname']}】，申请下级用户【{$activeUser['nickname']}】激活",
                'created_at' => time(),
                'type_id' => SysAccountModel::OP_CASH,
                'source' => SysAccountModel::OP_IN,
            ];
            if ($info['pay_type'] == 2) {
                $sysAccountData[] = [
                    'user_id' => $applier['id'],
                    'amount' => $need_integral,
                    'remark' => "运营中心【{$applier['nickname']}】，申请下级用户【{$activeUser['nickname']}】激活，支付{$this->setting['pay_integral_percent']}%积分{$need_integral}",
                    'created_at' => time(),
                    'type_id' => SysAccountModel::OP_INTEGRAL,
                    'source' => SysAccountModel::OP_IN,
                ];
                $sys_applier_data_1['remark'] .= "，支付{$this->setting['pay_balance_percent']}%现金{$need_balance}";
            } else {
                $sys_applier_data_1['remark'] .= "，支付现金{$need_balance}";
            }

            $sysAccountData[] = $sys_applier_data_1;
            M('SysAccount')->addAll($sysAccountData);

            //更改激活会员状态和身份识别码
            $User->where(['id' => $info['user_id']])->save([
                'identity' => 9,
                'activate_time' => time(),
            ]);
            //更改申请记录的状态
            $UserActiving->where(['id' => $info['id']])->save([
                'deal_at' => time(),
                'checker' => $this->admin_info['username'],
                'status' => 2
            ]);
            //更新上级的激活数量
            M('User')->where(['id' => $activeUser['inviter']])->setInc('invite_number');

            //系统转入激活用户与激活金额等额的积分（根据后台设置比例 可用和待用积分）和商品券
            $userGetActiveIntegral = 0;   //用户将会获得的可用积分
            $userGetUnstoreIntegral = 0;  //用户将会获得的待用积分
//            $userGetActiveIntegral = sprintf('%.2f', $this->setting['active_unstore_integral_percent'] / 100) * $info['amount'];
//            $userGetUnstoreIntegral = $info['amount'] - $userGetActiveIntegral;
            $userGetActiveIntegral = $info['amount'];
            $userGetUnstoreIntegral = $info['amount'] * (float)$this->setting['active_unstore_integral_multiple'];
            //不可倍增积分设置为多少$userGetActiveIntegral
            $UserWealth->where(['user_id' => $info['user_id']])->data([
                'integral' => ['exp', "integral+{$userGetActiveIntegral}"],
                'stored_integral' => ['exp', "stored_integral+{$userGetUnstoreIntegral}"],
                'unstore_integral' => ['exp', "unstore_integral+{$userGetActiveIntegral}"],
                'coupon' => ['exp', "coupon+{$info['amount']}"],
            ])->save();
            //待用积分数据表增加数据integral_bank
            M("IntegralBank")->add(
                [
                    'user_id' => $info['user_id'],
                    'amount' => $userGetUnstoreIntegral,
                    'returns' => $this->setting['active_unstore_integral_multiple'],
                    'cycle' => $this->setting['active_unstore_integral_cycle'],
                    'start_at' => time(),
                    'created_at' => time(),
                    'end_at' => mktime(0, 0, 0, date('m'), date('d') + $this->setting['active_unstore_integral_cycle'], date('Y')),
                    'status' => 1,
                    'from' => 1  //说是激活时返回的不可倍增积分
                ]
            );

            M('UserAccount')->addAll([
                [
                    'user_id' => $info['user_id'],
                    'amount' => $userGetActiveIntegral,
                    'balance' => $activeUser['integral'] + $userGetActiveIntegral,
                    'remark' => "账户激活成功，系统奖励可用积分{$userGetActiveIntegral}",
                    'created_at' => time(),
                    'type_id' => UserAccountModel::OP_INTEGRAL,
                    'source' => UserAccountModel::SC_IN,
                ],
                [
                    'user_id' => $info['user_id'],
                    'amount' => $userGetUnstoreIntegral,
                    'balance' => $activeUser['stored_integral'] + $userGetUnstoreIntegral,
                    'remark' => "账户激活成功，系统奖励待用积分{$userGetUnstoreIntegral}",
                    'created_at' => time(),
                    'type_id' => UserAccountModel::OP_UNSTORE_INTEGRAL,
                    'source' => UserAccountModel::SC_IN,
                ],
                [
                    'user_id' => $info['user_id'],
                    'amount' => $info['amount'],
                    'balance' => $activeUser['coupon'] + $info['amount'],
                    'remark' => "账户激活成功，系统奖励商品券{$info['amount']}",
                    'created_at' => time(),
                    'type_id' => UserAccountModel::OP_COUPON,
                    'source' => UserAccountModel::SC_IN,
                ]
            ]);

            M('SysAccount')->addAll(
                [
                    [
                        'user_id' => $info['user_id'],
                        'amount' => $userGetUnstoreIntegral,
                        'remark' => "【{$activeUser['nickname']}】用户激活成功，系统奖励待用积分{$userGetUnstoreIntegral}",
                        'created_at' => time(),
                        'type_id' => SysAccountModel::OP_UNSTORE_INTEGRAL,
                        'source' => SysAccountModel::OP_OUT,
                    ],
                    [
                        'user_id' => $info['user_id'],
                        'amount' => $userGetActiveIntegral,
                        'remark' => "【{$activeUser['nickname']}】用户激活成功，系统奖励可用积分{$userGetActiveIntegral}",
                        'created_at' => time(),
                        'type_id' => SysAccountModel::OP_INTEGRAL,
                        'source' => SysAccountModel::OP_OUT,
                    ],
                    [
                        'user_id' => $info['user_id'],
                        'amount' => $info['amount'],
                        'remark' => "【{$activeUser['nickname']}】用户激活成功，系统奖励商品券{$info['amount']}",
                        'created_at' => time(),
                        'type_id' => SysAccountModel::OP_COUPON,
                        'source' => SysAccountModel::OP_OUT,
                    ]
                ]
            );

            //直接上级获取10%倍数的积分，不可倍增
            $parent = M('User')->alias('A')->join(C('DB_PREFIX') . 'user_wealth as B ON A.id = B.user_id')
                ->where(['A.id' => $activeUser['inviter']])->find();
            if ($parent) {
                $parentGetIntegralPer = sprintf('%.2f', (($parent['invite_number'] * $this->setting['active_parent_integral_percent']) / 100));
                $parentGetIntegral = ($parentGetIntegralPer > 1 ? 1 : $parentGetIntegralPer) * $info['amount'];  //最大100%；

                M('UserWealth')->where(['user_id' => $parent['id']])->save([
                    'integral' => ['exp', "integral + {$parentGetIntegral}"],
                    'unstore_integral' => ['exp', "unstore_integral + {$parentGetIntegral}"],
                ]);
                M('UserAccount')->data([
                    'user_id' => $parent['id'],
                    'amount' => $parentGetIntegral,
                    'balance' => $parent['integral'] + $parentGetIntegral,
                    'remark' => "下级用户【{$activeUser['nickname']}】账户激活成功，系统奖励积分{$parentGetIntegral}",
                    'created_at' => time(),
                    'type_id' => UserAccountModel::OP_INTEGRAL,
                    'source' => UserAccountModel::SC_IN,
                ])->add();
                M('sysAccount')->data([
                    'user_id' => $parent['id'],
                    'amount' => $parentGetIntegral,
                    'remark' => "【{$activeUser['nickname']}】用户激活成功，系统奖励积分{$parentGetIntegral}",
                    'created_at' => time(),
                    'type_id' => SysAccountModel::OP_INTEGRAL,
                    'source' => SysAccountModel::OP_OUT,
                ])->add();
            }

            //隔代上级获取15%的积分报酬,比例$this->setting['active_user_reward']
            if (!empty($activeUser['p_parent'])) {
                $p_wealth = $UserWealth->find($activeUser['p_parent']['id']);
                $activeUser['p_parent'] = array_merge($activeUser['p_parent'], $p_wealth);

                $p_integral = sprintf('%.2f', $this->setting['active_user_reward'] / 100) * $info['amount'];
                $UserWealth->where(['user_id' => $activeUser['p_parent']['id']])->setInc('integral', $p_integral);
                M('UserAccount')->add([
                    'user_id' => $activeUser['p_parent']['id'],
                    'amount' => $p_integral,
                    'balance' => $activeUser['p_parent']['integral'] + $p_integral,
                    'remark' => "用户【{$activeUser['nickname']}】激活成功，获得可用积分奖励{$p_integral}",
                    'created_at' => time(),
                    'type_id' => UserAccountModel::OP_INTEGRAL,
                    'source' => UserAccountModel::SC_IN,
                ]);

                M('SysAccount')->add(
                    [
                        'user_id' => $activeUser['p_parent']['id'],
                        'amount' => $p_integral,
                        'remark' => "用户【{$activeUser['nickname']}】激活成功，系统派发积分奖励{$p_integral}给用户【{$activeUser['p_parent']['nickname']}】",
                        'created_at' => time(),
                        'type_id' => SysAccountModel::OP_INTEGRAL,
                        'source' => SysAccountModel::OP_OUT,
                    ]
                );
            }
        } catch (\Exception $e) {
            M()->rollback();
            $this->error($e->getMessage());
            return;
        }

        M()->commit();
        $this->success('用户激活成功');
    }

    //拒绝激活用户
    public function active_fail() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $info = M('UserActiving')->find($id);
        if (empty($info)) {
            $this->error('信息不存在');
        }
        if ($info['status'] != 0) {
            $this->error('该申请已处理');
        }

        if (IS_POST) {
            $msg = I('post.refuse_msg', '', 'trim');
            if (empty($msg)) {
                $this->error('请输入原因');
            }

            $result = M('UserActiving')->where(['id' => $info['id']])->data([
                'deal_at' => time(),
                'checker' => $this->admin_info['username'],
                'status' => 1,
                'refuse_msg' => $msg,
            ])->save();

            if ($result !== false) {
                $this->success('操作成功');
            }

            $this->error('操作失败');

        } else {
            $this->assign([
                'info' => $info,
            ]);
            $this->display();
        }
    }

    public function active_delete() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            return $this->error('参数错误');
        }

        $info = M('UserActiving')->where(['id' => $id])->find();
        if (empty($info)) {
            return $this->error('没有找到该记录');
        }
        if ($info['status'] == 1) {
            M('UserActiving')->where(['id' => $info['id']])->delete();
            return $this->success('删除成功');
        } else {
            return $this->error('该记录不能删除');
        }
    }

    public function identity() {
        $id = I('post.id', 0, 'intval');
        $identityId = I('post.identity', 9, 'intval');
        if (empty($id)) {
            return $this->error('参数错误');
        }
        if (!in_array($identityId, C('USER_IDENTITY'))) {
            $identityId = 9;
        }

        $user = M('User')->find($id);
        if (empty($user)) {
            return $this->error('用户不存在');
        }

        $result = M('User')->where(['id' => $user['id']])->data([
            'identity' => $identityId
        ])->save();

        if ($result !== false) {
            $this->clearUserCache();
            $this->success('身份更新成功');
        }
        $this->error('身份更新失败');
    }

    public function invite() {
        $cpage = (int)$_GET['p'] > 0 ? (int)$_GET['p'] : 1;
        $id = I('id', 0, 'intval');
        $where = [
            'inviter' => $id
        ];

        $User = M('User');

        $result = $User->where($where)->order('id DESC')->page($cpage, $this->page_size)->select();
        $count = $User->where($where)->count();
        $Page = new \Think\Page($count, $this->page_size);

        $this->assign([
            'id' => $id,
            'result' => $result,
            'page' => $Page->show(),
        ]);
        $this->display();
    }

    public function account() {
        $id = I('id', 0, 'intval');
        $where = [
            'user_id' => $id
        ];
        $total = M('UserAccount')->where($where)->count();
        $Page = new \Think\Page($total, $this->page_size);
        $result = M('UserAccount')->where($where)->page($Page->nowPage, $Page->listRows)->order('id DESC')->select();
        foreach ($result as $key => $val) {
            $result[$key]['created_at'] = format_time($val['created_at']);
        }

        $this->assign('id', $id);
        $this->assign('result', $result);
        $this->assign('page', $Page->show());
        $this->display();
    }

    public function password() {
        $id = I('id', 0, 'intval');
        if (IS_POST) {
            $password = I('password');
            if (strlen($password) < 6) {
                $this->error('密码不能小于6位');
            }
            $password = entrypt_password($password);
            M('User')->where(['id' => $id])->setField('password', $password);
            $this->success('密码修改成功');
        } else {
            $user_info = M('User')->where(['id' => $id])->field('id,mobile,nickname')->find();
            $this->assign($user_info);
            $this->display();
        }
    }

    public function lock() {
        $id = I('id', 0, 'intval');
        M('User')->where(['id' => $id])->setField('status', 'LOCKED');
        $this->success('锁定成功');
    }

    public function unlock() {
        $id = I('id', 0, 'intval');
        M('User')->where(['id' => $id])->setField('status', 'ACTIVE');
        $this->success('解锁成功');
    }

    public function mobile() {
        $id = I('id', 0, 'intval');
        $user_info = M('User')->find($id);
        if (IS_POST) {
            $mobile = I('mobile');
            if (!$mobile) {
                $this->error('请填写手机号码');
            }
            if (!isMobile($mobile)) {
                $this->error('手机号码不正确');
            }
            if ($mobile == $user_info['mobile']) {
                $this->error('新号码跟旧号码相同');
            }
            $total = M('User')->where(['mobile' => $mobile])->find();
            if ($total) {
                $this->error('该手机号码已经被使用');
            }
            M('User')->where(['id' => $id])->setField('mobile', $mobile);
            $this->success('修改成功');
        } else {
            $this->assign($user_info);
            $this->display();
        }
    }

    //增加，扣除
    public function pay() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            $this->error('参数错误');
            return;
        }

        $user = M('User')->find($id);
        if (empty($user)) {
            $this->error('该用户不存在');
            return;
        } else {
            $wealth = M('UserWealth')->where(['user_id' => $user['id']])->find();
            $user = array_merge($user, $wealth);
        }
        if (IS_POST) {
            $amount = I('amount', 0, 'floatval');
            $remark = I('remark', '', 'addslashes');
            $_type = I('_type', 1, 'intval');
            if ($amount == 0) {
                return $this->error('变动金额应该不等于0');
            }

            $types = ['coupon', 'integral', 'balance'];
            $typeIds = [UserAccountModel::OP_COUPON, UserAccountModel::OP_INTEGRAL, UserAccountModel::OP_CASH];
            $sysTypeIds = [SysAccountModel::OP_COUPON, SysAccountModel::OP_INTEGRAL, SysAccountModel::OP_CASH];

            if (!isset($types[$_type])) {
                $_type = 1;
            }

            $account = array(
                'user_id' => $user['id'],
                'amount' => abs($amount),
                'balance' => $user[$types[$_type]] + (float)$amount,
                'remark' => "系统转账，" . $remark,
                'created_at' => time(),
                'type_id' => $typeIds[$_type],
                'source' => $amount > 0 ? UserAccountModel::SC_IN : UserAccountModel::SC_OUT,
            );

            $data = [];
            $data = [
                $types[$_type] => ['exp', "{$types[$_type]} + {$amount}"],
            ];

            $sysAccount = [
                'user_id' => $user['id'],
                'amount' => (float)$amount,
                'remark' => "系统转账，" . $remark,
                'created_at' => time(),
                'type_id' => $sysTypeIds[$_type],
                'source' => $amount > 0 ? SysAccountModel::OP_OUT : SysAccountModel::OP_IN,
            ];

            $message = [
                'user_id' => $user['id'],
                'title' => '系统转账',
                'content' => '系统转账，' . $remark,
                'created_at' => time(),
            ];

            M()->startTrans();
            try {
                M('UserWealth')->where(array('user_id' => $user['id']))->save($data);
                M('UserAccount')->data($account)->add();
                M('SysAccount')->data($sysAccount)->add();
                M('Message')->data($message)->add();
            } catch (Exception $e) {
                M()->rollback();
                return $this->error($e->getMessage());
            }
            M()->commit();

            $this->success('操作成功');

        } else {

            $this->assign(array(
                'user' => $user,
            ));
            $this->display();
        }
    }

    //解除手机绑定 
    public function mobile_unbind() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            $this->error('参数错误');
        }

        $user = M('User')->find($id);
        if (empty($user)) {
            $this->error('该用户不存在');
        }

        if (M('User')->where(array('id' => $id))->setField(array('mobile' => '', 'mobile_bind' => 0)) !== false) {
            $this->success('解除成功');
        }

        $this->error('解除失败');
    }
}
